package com.u.iot.sleep.listener;

import org.eclipse.paho.mqttv5.client.*;
import org.eclipse.paho.mqttv5.common.MqttException;
import org.eclipse.paho.mqttv5.common.MqttMessage;
import org.eclipse.paho.mqttv5.common.packet.MqttProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * @program: u-InternetOfThings
 * @description: mqtt监听服务类
 * @author: Alex Wu
 * @createDate: 2025-03-19 17:22
 **/

//@Component
public class MqttListener {



    @Value("${mqtt.topic}")
    private String topic;


    private final Integer QOS = 1;

    @Autowired
    private MqttClient client;

    @EventListener(ApplicationReadyEvent.class) // Spring 完全启动后调用
    public void onApplicationReady() {
        try {

            client.setCallback(new MqttCallback() {


                @Override
                public void disconnected(MqttDisconnectResponse mqttDisconnectResponse) {

                }

                @Override
                public void mqttErrorOccurred(MqttException e) {

                }

                @Override
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    System.out.println("topic: " + topic);
                    System.out.println("qos: " + message.getQos());
                    System.out.println("message content: " + new String(message.getPayload()));

                }

                @Override
                public void deliveryComplete(IMqttToken iMqttToken) {

                }

                @Override
                public void connectComplete(boolean b, String s) {
                }

                @Override
                public void authPacketArrived(int i, MqttProperties mqttProperties) {

                }

                public void connectionLost(Throwable cause) {
                    System.out.println("connectionLost: " + cause.getMessage());
                }

                public void deliveryComplete(IMqttDeliveryToken token) {
                    System.out.println("deliveryComplete: " + token.isComplete());
                }
            });

            client.subscribe(topic, QOS);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
